#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <unistd.h>

#define NUM_TESTS 100      // 每个线程执行的操作次数
int num_flag = 0;//记录总运行次数

double max_time = 0.0;  // 记录总时间
pthread_mutex_t time_lock = PTHREAD_MUTEX_INITIALIZER;  // 用于保护 total_time 变量的锁

void *task_high(void *arg) {
    struct timespec start_time, end_time;
    printf("satrt task high\n");
    for (int i = 0; i < NUM_TESTS; i++)
    {
        clock_gettime(CLOCK_MONOTONIC, &start_time);
        usleep(100);
        clock_gettime(CLOCK_MONOTONIC, &end_time);

        double elapsed_time = (end_time.tv_sec - start_time.tv_sec) +
                            (end_time.tv_nsec - start_time.tv_nsec) /1.0e3 -100;
        if(max_time < elapsed_time)
        {
            max_time = elapsed_time;
        }

    }
    num_flag = 1;
}
int main() {
    pthread_t task_high_handle;  // 线程句柄
    pthread_t thread_main = pthread_self();  // 获取主线程的ID
    struct sched_param param;
    int policy = SCHED_RR;
    int result;
    param.sched_priority = 10;
    printf("satrt\n");

    // 设置调度策略为 SCHED_RR 10


    // 设置线程的调度策略和优先级
    if (pthread_setschedparam(thread_main, policy, &param) != 0) {
        perror("pthread_setschedparam");
        return -1;
    }

    printf("已设置主线程的调度策略为 SCHED_RR,优先级为: %d\n", param.sched_priority);
    pthread_attr_t attr;
     struct sched_param param1;
     // 初始化线程属性
    pthread_attr_init(&attr);

    // 设置线程的调度策略为 SCHED_FIFO，优先级为 10
    pthread_attr_setschedpolicy(&attr, SCHED_RR);
    param.sched_priority = 99;
    pthread_attr_setschedparam(&attr, &param1);

    // 创建线程并指定线程属性
    result = pthread_create(&task_high_handle, &attr, task_high, NULL);
    if (result != 0) {
        perror("pthread_create");
        return -1;
    }
    for(int i = 0; i < 100; i++)
    {
        if(num_flag == 0)
            i %= 99;
        else
            i = 100;//退出循环
    }

    // 等待所有线程完成
    if (pthread_join(task_high_handle, NULL) != 0) {
        perror("pthread_join failed");
        exit(1);
    }

    printf("\nMax time across all tests: %.3f us\n", max_time);



    return 0;
}

